package com.lovo.sheyingback.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lovo.sheyingback.bean.Function;
import com.lovo.sheyingback.bean.Role;
import com.lovo.sheyingback.dao.FunctionMapper;
import com.lovo.sheyingback.service.RoleService;
import com.lovo.sheyingback.dao.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author BDK-THINKPAD
* @description 针对表【t_role(角色表)】的数据库操作Service实现
* @createDate 2023-07-24 21:35:05
*/
@Service
public class RoleServiceImpl implements RoleService{
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private FunctionMapper functionMapper;
    @Override
    public PageInfo<Role> listRole(Integer current, Integer pageSize) {
        PageHelper.startPage(current,pageSize);
        List<Role> roles = roleMapper.listRole();
        return new PageInfo<>(roles);
    }

    @Override
    public Map listRoleFunction(Integer roleId) {
        List<Function> roleFunctions = functionMapper.listFunctionByRoleId(roleId);
        List<Function> allFunctions = functionMapper.listFunction();
//        List<Function> noAssignFunctions = allFunctions.stream()
//                .filter(function -> Collections.binarySearch(roleFunctions,function,(a, b) -> a.getId() - b.getId()) < 0)
//                .collect(Collectors.toList());
        return Map.of("all",allFunctions,"assign",roleFunctions);
    }

    @Override
    public Role getById(Integer id) {
        return roleMapper.getById(id);
    }

    @Override
    public int insert(Role role) {
        return roleMapper.insert(role);
    }

    @Override
    public int assignRoleFunction(Integer roleId, Integer[] functionIds) {
        roleMapper.deleteRoleFunction(roleId);
        for(Integer functionId : functionIds){
            roleMapper.insertRoleAndFunction(roleId,functionId);
        }
        return 1;
    }

    @Override
    public int update(Role role) {
        return roleMapper.update(role);
    }

    @Override
    @Transactional
    public int delete(Integer id) {
        roleMapper.deleteRoleUser(id);
        roleMapper.deleteRoleFunction(id);
        return roleMapper.delete(id);
    }
}




